/*******************************************************************************
 * Copyright (c) 2011, 2012 Link Management & Technology S.p.A. 
 * via R. Scotellaro, 55 - 73100 - Lecce - http://www.linksmt.it
 * All rights reserved. 
 *
 * Contributors:
 *     Links Management & Technology S.p.A. - initial API and implementation
 *******************************************************************************/
package it.linksmt.tooling.jpaddlplugin.impl;

import it.linksmt.tooling.jpaddlplugin.DDLParameters;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

import org.apache.maven.project.MavenProject;

/**
 * Custom classloader for loading classes from the host project. It adds
 * <ul>
 * <li>the target project's classes</li>
 * <li>the target project's test classes</li>
 * </ul>
 * @author Mario Scalas
 */
public class DDLClassLoader extends URLClassLoader {
	/**
	 * Factory method for creating the classloader: it adds the target project's classpath.
	 * 
	 * @param pluginClassLoader
	 * @param project
	 * @param params
	 * @return a new {@link DDLClassLoader} instance
	 * @throws RuntimeException if some directory name is wrong
	 */
	public static DDLClassLoader create( ClassLoader pluginClassLoader, MavenProject project, DDLParameters params ) {
		List<URL> urls = new ArrayList<URL>();
		try {
			File classDir = null;
			// Build classes
			classDir = new File( project.getBuild().getOutputDirectory() );
			urls.add( classDir.toURI().toURL() );
			// Test classes
			classDir = new File( project.getBuild().getTestOutputDirectory() );
			urls.add( classDir.toURI().toURL() );
		} catch (MalformedURLException e) {
			throw new RuntimeException( "Error while assembling classpath", e );
		}
		URL[] a = urls.toArray( new URL[0] );
		return new DDLClassLoader( a, pluginClassLoader );
	}
	
	/**
	 * @param urls
	 * @param parent
	 */
	private DDLClassLoader( URL[] urls, ClassLoader parent ) {
		super( urls, parent );
	}
}
